package com.example.rbacmanage.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordUtil {

    public static String sha256(String password) {
        try{
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(password.getBytes(java.nio.charset.StandardCharsets.UTF_8));
            return byteToHex(hash);
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        return null;
    }

    private static String byteToHex(byte[] hash) {
        StringBuffer stringBuffer = new StringBuffer(2 * hash.length);
        for (int i=0; i<hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            stringBuffer.append(hex);
        }
        return stringBuffer.toString();
    }
    public static boolean checkPassword(String password, String storedPassword) {
        String passwordHash = sha256(password);
        return storedPassword.equals(passwordHash);
    }

}
